import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/widget/common/count_text.dart';
import 'package:material_collection_app/widget/common/empty_tips.dart';
import 'package:material_collection_app/widget/common/search_box.dart';
import 'package:material_collection_app/widget/common/date_select.dart';
import 'package:material_collection_app/widget/manage/mange_card.dart';
import 'package:material_collection_app/widget/common/refresh.dart';
import 'package:material_collection_app/widget/common/top_bar.dart';
import '../utils/utils.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class ManagePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyState();
}

class MyState extends State<ManagePage> {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  String validStartDate = '';
  String validEndDate = '';
  String enStartDate = '';
  String enEndDate = '';
  List list = [];
  int currentPage = 1;
  int lastPage = 1;
  int total = 0;
  bool loadSuccess = false;
  String keywords;
  int goodsTypeId;
  List materialTypeList = [];
  bool materialLoadSuccess = false;
  int materialTypeIndex;

  @override
  void initState() {
    super.initState();
    _setDefaultScreen();
    _loadData();
    _getMaterialType();
  }

  // 设置默认筛选条件
  _setDefaultScreen() {
    // String currentTime = new DateTime.now().toString().substring(0, 10);
    setState(() {
      goodsTypeId = null;
      validStartDate = '开始日期';
      validEndDate = '结束日期';
      enStartDate = '开始日期';
      enEndDate = '结束日期';
      materialTypeIndex = null;
    });
  }

  // 加载数据
  _loadData({bool loadMore = false, bool screen}) async {
    loadSuccess = false;

    if (loadMore) {
      currentPage++;
    } else {
      currentPage = 1;
    }

    Map params = {
      'page': currentPage,
      'key': keywords,
    };

    if (screen == true) {
      params['goods_type_id'] = goodsTypeId;
    }

    if (validStartDate != '开始日期') {
      params['valid_time_start'] = validStartDate;
      params['valid_time_end'] = validEndDate;
    }

    if (enStartDate != '开始日期') {
      params['create_time_start'] = enStartDate;
      params['create_time_end'] = enEndDate;
    }

    DioUtils.request("goods/lists",
        context: context, method: "POST", params: params, onSuccess: (res) {
      if (res['code'] == 1) {
        if (mounted) {
          setState(() {
            if (loadMore) {
              list.addAll(res["data"]["data"]);
            } else {
              list = res["data"]["data"];
            }

            currentPage = res['data']['current_page'];
            lastPage = res['data']['last_page'];
            loadSuccess = true;
            total = res['data']['total'];
          });
        }
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {});
  }

  // 获取物资类型
  _getMaterialType() async {
    materialLoadSuccess = false;

    DioUtils.request("goods/TypeAddInstall",
        context: context, method: "POST", params: {}, onSuccess: (res) {
      if (res['code'] == 1) {
        if (mounted) {
          setState(() {
            materialTypeList = res["data"]["parent"];
            materialLoadSuccess = true;
          });
        }
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {});
  }

  // 下拉刷新
  _onRefresh() async {
    _refreshController.loadComplete();
    _loadData();

    await Future.delayed(Duration(milliseconds: 600));
    _refreshController.refreshCompleted();
  }

  // 加载更多
  _onLoading() async {
    await Future.delayed(Duration(milliseconds: 200));

    if (currentPage == lastPage) {
      _refreshController.loadNoData();
      return;
    }

    // 加载更多数据
    if (currentPage < lastPage) {
      _loadData(loadMore: true);
      _refreshController.loadComplete();
    }
  }

  Widget _buildCardLine() {
    return Container(
      width: double.infinity,
      height: 1,
      margin: EdgeInsets.symmetric(vertical: 29.w),
      color: Utils.hexToColor('#FBFBFB'),
    );
  }

  Widget _buildCardTitle(title) {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.only(bottom: 10.w, top: 10.w),
      child: Text(
        title,
        style: TextStyle(
            color: Utils.hexToColor('#676767'), fontSize: 12, height: 1),
      ),
    );
  }

  Widget _buildCard() {
    List<Widget> content = [];

    for (int i = 0; i < materialTypeList.length; i++) {
      var item = materialTypeList[i];
      content.add(InkWell(
          onTap: () {
            setState(() {
              materialTypeIndex = i;
              goodsTypeId = item['id'];
            });
          },
          child: Container(
              width: 190.w,
              height: 76.w,
              alignment: Alignment.center,
              color: Utils.hexToColor(
                  materialTypeIndex == i ? '#E9F2FF' : '#F8F8F8'),
              child: Text(item['type_name'],
                  style: TextStyle(
                      color: Utils.hexToColor(
                          materialTypeIndex == i ? '#297CFF' : '#676767'),
                      fontSize: 12,
                      fontWeight: materialTypeIndex == i
                          ? FontWeight.bold
                          : FontWeight.w500)))));
    }

    return Wrap(
      spacing: 10.w,
      runSpacing: 10.w,
      crossAxisAlignment: WrapCrossAlignment.start,
      children: content,
    );
  }

  Widget _buildPage() {
    // // 无数据
    if (loadSuccess && list.length == 0) {
      return EmptyTips(
        refreshController: _refreshController,
        onRefresh: _onRefresh,
        backgroundColor: Utils.hexToColor('#F7F6F9'),
      );
    }

    return ListView.builder(
        itemCount: list.length,
        padding: EdgeInsets.only(bottom: 60.w),
        itemBuilder: (BuildContext context, int index) {
          return ManageCard(item: list[index]);
        });
  }

  Widget _buildEndDrawer() {
    return Drawer(
        child: Container(
            color: Colors.white,
            padding: EdgeInsets.fromLTRB(20.w, 78.w, 20.w, 34.w),
            child: Stack(children: <Widget>[
              SingleChildScrollView(
                child: Container(
                  padding: EdgeInsets.only(bottom: 60),
                  child: Column(children: <Widget>[
                    _buildCardTitle('物资类型'),
                    _buildCard(),
                    _buildCardLine(),
                    Column(children: <Widget>[
                      _buildCardTitle('有效期'),
                      Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            DateSelect(
                              defaultDate: validStartDate,
                              resetDate: () {
                                setState(() {
                                  validStartDate = '';
                                });
                              },
                              onConfirm: (date) => {
                                setState(() {
                                  validStartDate = date;
                                })
                              },
                            ),
                            Text(
                              '—',
                              style:
                                  TextStyle(color: Utils.hexToColor('#999999')),
                            ),
                            DateSelect(
                                defaultDate: validEndDate,
                                resetDate: () {
                                  setState(() {
                                    validEndDate = '';
                                  });
                                },
                                onConfirm: (date) => {
                                      setState(() {
                                        validEndDate = date;
                                      })
                                    })
                          ])
                    ]),
                    Container(
                      margin: EdgeInsets.only(top: 30.w),
                      padding: EdgeInsets.only(top: 30.w),
                      decoration: BoxDecoration(
                          border: Border(
                              top: BorderSide(
                                  color: Utils.hexToColor('#FBFBFB')))),
                      child: Column(children: <Widget>[
                        _buildCardTitle('入库时间'),
                        Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: <Widget>[
                              DateSelect(
                                defaultDate: enStartDate,
                                resetDate: () {
                                  setState(() {
                                    enStartDate = '';
                                  });
                                },
                                onConfirm: (date) => {
                                  setState(() {
                                    enStartDate = date;
                                  })
                                },
                              ),
                              Text(
                                '—',
                                style: TextStyle(
                                    color: Utils.hexToColor('#999999')),
                              ),
                              DateSelect(
                                  defaultDate: enEndDate,
                                  resetDate: () {
                                    setState(() {
                                      enEndDate = '';
                                    });
                                  },
                                  onConfirm: (date) => {
                                        setState(() {
                                          enEndDate = date;
                                        })
                                      })
                            ])
                      ]),
                    )
                  ]),
                ),
              ),
              // DrawerButtons()
              Align(
                  alignment: Alignment.bottomCenter,
                  child: Container(
                      child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                        Container(
                          // margin: EdgeInsets.only(top: 70.w),
                          child: SizedBox(
                            width: 250.w,
                            height: 76.w,
                            child: ElevatedButton(
                              onPressed: () {
                                _setDefaultScreen();
                              },
                              child: Container(
                                margin: EdgeInsets.only(left: 16.w),
                                child: Text(
                                  '重置',
                                  style: TextStyle(color: Colors.white),
                                ),
                              ),
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Utils.hexToColor('#FF9232'),
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.horizontal(
                                        left: Radius.circular(60.w))),
                              ),
                            ),
                          ),
                        ),
                        Container(
                            // margin: EdgeInsets.only(top: 70.w),
                            child: SizedBox(
                                width: 250.w,
                                height: 76.w,
                                child: ElevatedButton(
                                  onPressed: () {
                                    _loadData(screen: true);
                                    Navigator.pop(context);
                                  },
                                  child: Container(
                                    margin: EdgeInsets.only(left: 16.w),
                                    child: Text(
                                      '确定',
                                      style: TextStyle(color: Colors.white),
                                    ),
                                  ),
                                  style: ElevatedButton.styleFrom(
                                      backgroundColor: Color(0xFF297CFF),
                                      shape: RoundedRectangleBorder(
                                          borderRadius: BorderRadius.horizontal(
                                              right: Radius.circular(60.w)))),
                                )))
                      ])))
            ])));
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return Scaffold(
        appBar: TopBar(
          height: 0,
        ),
        body: Container(
            color: Utils.hexToColor('#F5F6FA'),
            child: Column(children: <Widget>[
              SearchBox(
                hintText: '名称',
                onSearch: (value) {
                  setState(() {
                    keywords = value;
                  });
                  _loadData();
                },
              ),
              CountText(number: total),
              Expanded(
                  child: Container(
                      padding: EdgeInsets.fromLTRB(25.w, 23.w, 25.w, 0),
                      child: Refresh(
                          refreshController: _refreshController,
                          onRefresh: _onRefresh,
                          onLoading: _onLoading,
                          headBottom: 10,
                          child: _buildPage())))
            ])),
        endDrawer: _buildEndDrawer());
  }
}
